package com.web.common.sql;


import com.web.common.utils.StringUtils;

import java.util.List;

/**
 * sql操作工具类
 *
 * @author jeethink www.jeethink.vip
 */
public class SqlUtil{
    /**
     * 仅支持字母、数字、下划线、空格、逗号（支持多个字段排序）
     */
    public static String SQL_PATTERN = "[a-zA-Z0-9_\\ \\,]+";

    /**
     * 检查字符，防止注入绕过
     */
    public static String escapeOrderBySql(String value) {
        if (StringUtils.isNotEmpty(value) && !isValidOrderBySql(value)) {
            return StringUtils.EMPTY;
        }
        return value;
    }

    /**
     * 验证 order by 语法是否符合规范
     */
    public static boolean isValidOrderBySql(String value) {
        return value.matches(SQL_PATTERN);
    }



    public static String getNotInsqlNumber(List<String> strList) {

        if (strList == null || strList.size() == 0) return null;
        int paramSize = strList.size();
        StringBuffer sbf = new StringBuffer(" not in(");
        for (int index = 0; index < paramSize; index++) {
            if (index == 0) sbf.append(strList.get(index));
            if (index > 0) sbf.append(",").append(strList.get(index));
        }
        sbf.append(")");

        return sbf.toString();
    }

    public static String getinSqlNumber(List<Integer> strList) {

        if (strList == null || strList.size() == 0) {
            return null;
        }

        int paramSize = strList.size();
        StringBuffer sbf = new StringBuffer(" in (");
        for (int index = 0; index < paramSize; index++) {
            if (index == 0) sbf.append(strList.get(index));
            if (index > 0) sbf.append(",").append(strList.get(index));
        }
        sbf.append(")");

        return sbf.toString();
    }

    public static String getinSqlNumber1(List<String> strList) {

        if (strList == null || strList.size() == 0) {
            return null;
        }

        int paramSize = strList.size();
        StringBuffer sbf = new StringBuffer(" in(");
        for (int index = 0; index < paramSize; index++) {
            if (index == 0) sbf.append(strList.get(index));
            if (index > 0) sbf.append(",").append(strList.get(index));
        }
        sbf.append(")");

        return sbf.toString();
    }

    public static String getinsqlString(List<String> strList) {

        if (strList == null || strList.size() == 0) return null;
        int paramSize = strList.size();
        StringBuffer sbf = new StringBuffer("in (");
        for (int index = 0; index < paramSize; index++) {
            if (index == 0) sbf.append("'").append(strList.get(index)).append("'");
            if (index > 0) sbf.append(",'").append(strList.get(index)).append("'");
        }
        sbf.append(")");

        return sbf.toString();
    }

}
